<template>
  <div class="inbound-view">
    <el-card>
      <div slot="header">
        <span>入库管理</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="showAddDialog">
          <i class="el-icon-plus"></i> 新增入库记录
        </el-button>
      </div>
      <!-- 查询区域 -->
      <el-form :inline="true" :model="queryForm" class="demo-form-inline">
        <el-form-item label="订单号">
          <el-input v-model="queryForm.orderId" placeholder="请输入订单号"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <!-- 数据展示 -->
      <div v-if="currentInBound">
        <el-descriptions title="入库信息" :column="2" border>
          <el-descriptions-item label="订单号">{{currentInBound.order_id}}</el-descriptions-item>
          <el-descriptions-item label="车牌号">{{currentInBound.plate_id}}</el-descriptions-item>
          <el-descriptions-item label="入库件数">{{currentInBound.qte_in}}</el-descriptions-item>
          <el-descriptions-item label="入库吨数">{{currentInBound.weight_in}}</el-descriptions-item>
          <el-descriptions-item label="入库时间">{{currentInBound.time_in}}</el-descriptions-item>
        </el-descriptions>

        <div style="margin-top: 20px;">
          <!-- 主要按钮-->
          <el-button type="primary" @click="showEditDialog">编辑</el-button>
          <!--危险操作-->
          <el-button type="danger" @click="handleDelete">删除</el-button>
        </div>
      </div>

      <div v-else-if="!hasQueried" class="empty-state">
        <i class="el-icon-search"></i>
        <p>请输入订单号进行查询</p>
      </div>

      <div v-else class="empty-state">
        <i class="el-icon-warning"></i>
        <p>未找到相关入库信息</p>
      </div>
    </el-card>
    <!-- 新增/编辑对话框 -->
                <!-- 动态标题新增/编辑通用 -->    <!-- 控制显示隐藏 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px">
      <!-- 创建表单 -->
      <el-form :model="inBoundForm" :rules="rules" ref="inBoundForm" label-width="100px">
        <el-form-item label="订单号" prop="order_id">
          <!-- 编辑模式禁用 -->
          <el-input v-model="inBoundForm.order_id" :disabled="isEdit"></el-input>
        </el-form-item>
        <el-form-item label="车牌号" prop="plate_id">
          <el-input v-model="inBoundForm.plate_id"></el-input>
        </el-form-item>
        <el-form-item label="入库件数" prop="qte_in">
          <el-input-number v-model="inBoundForm.qte_in" :precision="2" :step="0.01" :min="0"></el-input-number>
        </el-form-item>
        <el-form-item label="入库吨数" prop="weight_in">
          <el-input-number v-model="inBoundForm.weight_in" :precision="2" :step="0.01" :min="0"></el-input-number>
        </el-form-item>
        <el-form-item label="入库时间" prop="time_in">
          <el-date-picker
            v-model="inBoundForm.time_in"
            type="date"
            placeholder="请选择入库时间"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { inBoundAPI } from '@/api/api'
export default{
  name: 'InBoundView',
  data(){
    return{
      queryForm:{
        orderId: ''
      },
      /* 当前选中的入库记录 */
      currentInBound:null,
      /* 标记是否已执行过查询 */
      hasQueried:false,
      /* 控制弹窗（对话框）的显示/隐藏 */
      dialogVisible:false,
      /* 标记当前是否为编辑模式 */
      isEdit:false,
      inBoundForm:{
        order_id:'',
        user_id:null,
        plate_id:'',
        qte_in:null,
        weight_in:null,
        time_in:''
      },
      /* 表单验证规则 */
      rules:{
        order_id:[
          /* 设置为必填 */
          {required: true, message:'请输入订单号', trigger: 'blur'}
        ],
        plate_id:[
          {required: true, message:'请输入车牌号', trigger: 'blur'}
        ],
        qte_in:[
          {required: true, message:'请输入入库件数', trigger: 'blur'}
        ],
        weight_in:[
          {required: true, message:'请输入入库吨数', trigger: 'blur'}
        ],
        time_in:[
          {required: true, message:'请输入入库时间', trigger: 'change'}
        ]
      }
    }
  },
  computed:{
    dialogTitle(){
      return this.isEdit ? '编辑入库记录' : '新增入库记录'
    }
  },
  methods:{
    async handleQuery(){
      if(!this.queryForm.orderId){
        this.$message.warning('请输入订单号')
        return
      }
      try{
        const response = await inBoundAPI.select(this.queryForm.orderId)
        if(response && response.code === 200 && response.data){
          this.currentInBound = response.data
          this.hasQueried = true
          this.$message.success('查询成功')
        }
        else{
          this.currentInBound = null
          this.hasQueried = true
          this.$message.warning('未找到相关入库信息')
        }
      }catch(error){
        console.error('查询失败:', error)
        this.currentInBound = null
        this.hasQueried = true
        this.$message.error('查询失败')
      }
    },
    /* 重置查询表单和相关的查询结果状态 */
    resetQuery(){
      this.queryForm.orderId = ''
      this.currentInBound = null
      this.hasQueried = false
    },
    /* 显示新增模式的弹窗 */
    showAddDialog(){
      /* 新增模式 */
      this.isEdit = false
      /* 初始化 */
      let user = localStorage.getItem('user')
      let user_id = ''
      if (user) {
        try {
          user_id = JSON.parse(user).user_id
        } catch (e) {}
      }
      this.inBoundForm = {
        order_id: '',
        user_id: user_id,
        plate_id: '',
        qte_in: null,
        weight_in: null,
        time_in: ''
      }
      /* 显示弹窗 */
      this.dialogVisible = true;
    },
    /* 显示编辑模式的弹窗 */
    showEditDialog(){
      this.isEdit = true
      this.inBoundForm = {...this.currentInBound}
      this.dialogVisible = true
    },
    /* 表单提交 */
    async handleSubmit(){
      this.$refs.inBoundForm.validate(async (valid) => {
        if(valid){
          try{
            if(this.isEdit){
              const response = await inBoundAPI.update(this.inBoundForm)
              if(response && response.code === 200){
                this.$message.success('更新成功')
              } else {
                this.$message.error('更新失败')
                return
              }
            }
            else{
              const response = await inBoundAPI.add(this.inBoundForm)
              if(response && response.code === 200){
                this.$message.success('添加成功')
                this.currentInBound = response.data
                this.hasQueried = true
              } else {
                this.$message.error('添加失败')
                return
              }
            }
            /* 弹窗隐藏 */
            this.dialogVisible = false
          }catch(error){
            console.error('操作失败:', error)
            this.$message.error(this.isEdit ? '更新失败' : '添加失败')
          }
        }
      })
    },
    async handleDelete(){
      /* 二次窗口 */
      this.$confirm('确认删除该入库记录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try{
          const response = await inBoundAPI.delete(this.currentInBound.order_id)
          if(response && response.code === 200){
            this.$message.success('删除成功')
            this.resetQuery()
          } else {
            this.$message.error('删除失败')
          }
        }catch(error){
          console.error('删除失败:', error)
          this.$message.error('删除失败')
        }
      })
    }
  }
}
</script>

<style scoped>
.inbound-view{
  padding: 20px;
}

.empty-state{
  text-align: center;
  padding: 40px;
  color: #909399;
}

.empty-state i{
  font-size: 48px;
  margin-bottom: 16px;
}

.empty-state p{
  margin: 0;
  font-size: 14px;
}
</style>